﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using Mindfor.Web.Data;
using System.Reflection;

namespace Mindfor.Web.Config
{
	/// <summary>
	/// Represents data provider config section.
	/// </summary>
	public sealed class DataProviderElement : ConfigurationElement
	{
		/// <summary>
		/// Gets or sets data provider type.
		/// </summary>
		[ConfigurationProperty("providerType", DefaultValue="Mindfor.Web.Data.SqlServer2008DataProvider, Mindfor.WebMP", IsRequired = false)]
		public string ProviderType
		{
			get { return (string)this["providerType"]; }
			set { this["providerType"] = value; }
		}

		/// <summary>
		/// Gets or sets data provider connection string name.
		/// </summary>
		[ConfigurationProperty("connectionStringName", IsRequired=true)]
		public string ConnectionStringName
		{
			get { return (string)this["connectionStringName"]; }
			set { this["connectionStringName"] = value; }
		}

		/// <summary>
		/// Gets connections string by name that is set in data provider config.
		/// </summary>
		public ConnectionStringSettings ConnectionData
		{
			get { return ConfigurationManager.ConnectionStrings[ConnectionStringName]; }
		}

		/// <summary>
		/// Initializes new <see cref="Mindfor.WebMP.Data.IDataProvider"/>.
		/// </summary>
		public IDataProvider CreateInstance()
		{
			// try to find full typename
			if (!String.IsNullOrEmpty(ProviderType))
			{
				string[] s = ProviderType.Split(',');
				if (s.Length > 1)
				{
					string typeName = s[0].Trim();
					string assembly = s[1].Trim();

					string fullTypeName = Assembly.CreateQualifiedName(assembly, typeName);
					Type type = Type.GetType(fullTypeName);

					//try to create instance
					if (type != null)
					{
						object provider = Activator.CreateInstance(type, ConnectionData.ConnectionString);
						if (provider is IDataProvider)
							return (IDataProvider)provider;
						else
							throw new CmsConfigException("Specified data provider does not implements IDataProvider interface.");
					}
				}
			}

			throw new CmsConfigException("Can not find data provider specified in <mindfor.webmp> config section.");
		}
	}
}
